package com.bandaotixi.cashier.api.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.bandaotixi.cashier.api.common.model.Option;
import com.bandaotixi.cashier.api.common.result.Result;
import com.bandaotixi.cashier.api.system.model.entity.Menu;
import com.bandaotixi.cashier.api.system.model.query.MenuQuery;
import com.bandaotixi.cashier.api.system.model.vo.MenuVO;
import com.bandaotixi.cashier.api.system.model.vo.RouteVO;
import com.bandaotixi.cashier.api.system.service.MenuService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单控制层
 */
@RestController
@RequestMapping("/menus")
@RequiredArgsConstructor
@Slf4j
public class MenuController {

    private final MenuService menuService;

    @SaCheckPermission("sys:menu")
    @GetMapping
    public Result<List<MenuVO>> listMenus(MenuQuery queryParams) {
        List<MenuVO> menuList = menuService.listMenus(queryParams);
        return Result.success(menuList);
    }

    @GetMapping("/options")
    public Result<List<Option<Long>>> listMenuOptions(@RequestParam(required = false, defaultValue = "false") boolean onlyParent) {
        List<Option<Long>> menus = menuService.listMenuOptions(onlyParent);
        return Result.success(menus);
    }

    @GetMapping("/routes")
    public Result<List<RouteVO>> getCurrentUserRoutes() {
        List<RouteVO> routeList = menuService.getCurrentUserRoutes();
        return Result.success(routeList);
    }

    @SaCheckPermission("sys:menu")
    @GetMapping("/{id}/form")
    public Result<Menu> getMenuForm(@PathVariable Long id) {
        Menu menu = menuService.getById(id);
        return Result.success(menu);
    }

    @SaCheckPermission("sys:menu")
    @PostMapping
    public Result<?> addMenu(@RequestBody Menu menuForm) {
        boolean result = menuService.save(menuForm);
        return Result.judge(result);
    }

    @SaCheckPermission("sys:menu")
    @PutMapping(value = "/{id}")
    public Result<?> updateMenu(@RequestBody Menu menuForm) {
        boolean result = menuService.save(menuForm);
        return Result.judge(result);
    }

    @SaCheckPermission("sys:menu")
    @DeleteMapping("/{id}")
    public Result<?> deleteMenu(@PathVariable("id") Long id) {
        boolean result = menuService.removeById(id);
        return Result.judge(result);
    }

    @SaCheckPermission("sys:menu")
    @PatchMapping("/{menuId}")
    public Result<?> updateMenuVisible(@PathVariable Long menuId,Integer visible) {
        boolean result = menuService.lambdaUpdate()
                .eq(Menu::getId, menuId)
                .set(Menu::getVisible, visible).update();
        return Result.judge(result);
    }

}

